<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-useDeptName>
            <slip-select
              v-model="filterInfo.query.queryParams.useDeptIdMult"
              value-key="value"
              placeholder="选择使用部门"
              :api="inOrOutDepotInfo.api"
              key-field="name"
              value-field="id"
              :query="inOrOutDepotInfo.query"
              :clearable="true"
              :filterable="true"
              :multiple="true"
              @change="search"
            />
          </template>
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-remove>
            <el-button
              :disabled="!tableInfo.selections.length"
              @click="remove()"
              >删除</el-button
            >
          </template>
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="true"
        :tab-index="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="scope.row.status !== 1"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else>{{ scope.row.orderNo }}</span>
        </template>
        <template v-slot:col-inventoryPercent="scope">
          <span>{{ scope.row.inventoryPercent || 0 }} %</span>
        </template>
      </table-container>
    </div>

    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <!--<div class="dialogInfo-form-title">基本信息</div>-->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
        @handleEvent="handleEventFrom"
      >
        <template v-slot:form-planResponseUser>
          <el-input
            v-model="formInfo.data.planResponseUserName"
            type="input"
            class="not-mongolia"
            :disabled="true"
            placeholder="请选计划负责人"
          >
            <template #append>
              <el-icon @click="openPlanResponseUser"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
      <div class="dialogInfo-form-title">
        盘点范围<span>(不选择范围则默认为所有设备)</span>
      </div>
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.rangeRef"
        :data="formInfo.data"
        :field-list="formInfo.fieldListRange"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-inventoryUseDeptId>
          <el-input
            v-model="formInfo.data.inventoryUseDeptName"
            type="input"
            class="not-mongolia"
            :disabled="true"
            placeholder="请选择使用部门"
          >
            <template #append>
              <el-icon @click="openUseDeptWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-inventoryDepotName>
          <el-input
            v-model="formInfo.data.inventoryDepotName"
            type="input"
            class="not-mongolia"
            :disabled="true"
            placeholder="请选择仓库"
          >
            <template #append>
              <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-inventoryManageDeptId>
          <el-input
            v-model="formInfo.data.inventoryManageDeptName"
            type="input"
            class="not-mongolia"
            :disabled="true"
            placeholder="请选择管理部门"
          >
            <template #append>
              <el-icon @click="openManageDeptWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-inventoryDeviceType>
          <el-input
            v-model="formInfo.data.inventoryDeviceTypeValue"
            type="input"
            class="not-mongolia"
            :disabled="true"
            placeholder="请选择医疗器械分类目录"
          >
            <template #append>
              <el-icon @click="openDeviceTypeWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-inventoryRangeAssetList>
          <el-input
            v-model="formInfo.assetName"
            class="not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择盘点资产"
          >
            <template #append>
              <el-icon @click="selectAsset"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>

    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row-id="detailInfo.id"
      @returnBack="getList"
    />
    <!-- 选择资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :queryParams="selectAssetInfo.query.queryParams"
      :check-box="true"
      :saveEmpty="true"
      :checked-row-list="selectAssetInfo.checkedRowList"
      :table-key="selectAssetInfo.tableKey"
      @callback="callbackAsset"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!-- 选择人员 -->
    <SelectUsers
      v-if="planResponseUserInfo.visible"
      v-model:show-dialog="planResponseUserInfo.visible"
      :query="planResponseUserInfo.query"
      :api="planResponseUserInfo.api"
      :check-box="false"
      :highlight-row="true"
      @callback="selectPlanResponseUser"
    />
    <select-dept
      v-if="useDeptInfo.visible"
      v-model:show-dialog="useDeptInfo.visible"
      :query="useDeptInfo.query"
      :checked-row-list="useDeptInfo.checkedRowList"
      :check-box="true"
      :highlight-row="false"
      :save-empty="true"
      @callback="selectUseDeptCallback"
    />
    <select-dept
      v-if="manageDeptInfo.visible"
      v-model:show-dialog="manageDeptInfo.visible"
      :query="manageDeptInfo.query"
      :check-box="true"
      :highlight-row="false"
      :checked-row-list="manageDeptInfo.checkedRowList"
      :save-empty="true"
      @callback="selectManageDeptCallback"
    />
    <SelectSettingClassification
      v-if="deviceTypeInfo.visible"
      v-model:show-dialog="deviceTypeInfo.visible"
      :save-empty="true"
      :check-box="true"
      :highlight-row="false"
      :checked-row-list="deviceTypeInfo.checkedRowList"
      @callback="selectDeviceTyprCallBack"
    />
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="true"
      :highlight-row="false"
      :query="selectDepotInfo.query"
      :save-empty="true"
      :checked-row-list="selectDepotInfo.checkedRowList"
      @callback="selectDepotCallBack"
    />
    <!-- 数据录入-->
    <page-dialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="assetInventoryPlan">
import { getDeptAll, getDepotAll } from '@/api/core.js'
import { getCurrentFiscalPeriod } from '@/api/core.js'
import { getRrgUserList, fatchTemplateByCode } from '@/api/base.js'
import {
  publishInventoryOrderPlan,
  createInventoryOrderPlan,
  getInventoryOrderPlanPage,
  revokeInventoryOrderPlan,
  closeInventoryOrderPlan,
  updateInventoryOrderPlan,
  excelInventoryPlanOrderList,
  getInventoryOrderPlanById,
  inventoryPlanOrderExcelOffline,
  inventoryPlanOrderOfflinePrint,
  printInventoryPlanOrderList,
  deleteInventoryOrderPlan,
  confirmInventoryOrderPlan,
  getClassificationAll,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const OrderDetail = defineAsyncComponent(() => import('./details'))

const { proxy } = getCurrentInstance()

const dialogTipsInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const inOrOutDepotInfo = reactive({
  api: getDeptAll,
  query: {
    assetSourceAuth: true,
    status: 1,
  },
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      isAssetAchievesExcel: 'true',
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetInventoryPlan:add'),
    },
    {
      type: 'slot',
      value: 'remove',
      show: proxy.$permission('assetInventoryPlan:del'),
    },
    {
      type: 'slot',
      value: 'download',
      show: proxy.$permission('assetInventoryPlan:excel'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetInventoryPlan:printOrder'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '发布',
        event: publish,
        show: proxy.$permission('assetInventoryPlan:publish'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetInventoryPlan:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: remove,
        show: proxy.$permission('assetInventoryPlan:del'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('assetInventoryPlan:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '确认',
        event: confirmPlan,
        show: proxy.$permission('assetInventoryPlan:confirm'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
      {
        label: '关闭',
        event: closePlan,
        popconfirmText: '关闭后将改变数据,是否继续？',
        show: proxy.$permission('assetInventoryPlan:close'),
        ifRender: function (row) {
          return [2, 4].includes(row.status)
        },
      },

      {
        label: '打印盘点单',
        event: printOffline,
        show: proxy.$permission('assetInventoryPlan:printOffline'),
        ifRender: function (row) {
          return [2, 4].includes(row.status)
        },
      },
      {
        label: '导出盘点单',
        event: excelOffline,
        show: proxy.$permission('assetInventoryPlan:excelOffline'),
        ifRender: function (row) {
          return [2, 4].includes(row.status)
        },
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '新增盘点计划',
  visible: false,
  type: '',
  width: '50%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
// 表单相关
const formInfo = ref({
  ref: null,
  rangeRef: null,
  assetName: '',
  data: {
    planResponseUser: '',
    inventoryUseDeptId: '',
    inventoryManageDeptId: '',
    inventoryDeviceType: '',
    planResponseUserName: '',
    inventoryUseDeptName: '',
    inventoryManageDeptName: '',
    inventoryAssetTypeValue: '',
    inventoryDeviceTypeValue: '',
    businessDate: '',
    inventoryRangeAssetList: [],
    remark: '',
    inventoryDepotId: '',
    inventoryDepotName: '',
  },
  fieldList: [
    {
      label: '盘点位置',
      value: 'inventoryLocation',
      type: 'radio-model',
      code: 'asset_inventory_location',
      event: 'inventoryLocation',
    },
    {
      label: '盘点名称',
      value: 'planName',
      type: 'input',
    },
    {
      label: '计划开始日期',
      value: 'planStartDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '计划负责人',
      value: 'planResponseUser',
      type: 'slot',
    },
    {
      label: '计划结束日期',
      value: 'planEndDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '任务拆解维度',
      value: 'splitType',
      type: 'select-model',
      code: 'asset_inventory_split_type',
      onlyShowOption: ['1', '2', '3', '4', '5'],
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  fieldListRange: [
    {
      label: '使用部门',
      value: 'inventoryUseDeptId',
      type: 'slot',
    },
    {
      label: '仓库',
      value: 'inventoryDepotName',
      type: 'slot',
      show: false,
    },
    {
      label: '管理部门',
      value: 'inventoryManageDeptId',
      type: 'slot',
    },
    {
      label: '医疗器械分类目录',
      value: 'inventoryDeviceType',
      type: 'slot',
    },
    {
      label: '选择资产',
      value: 'inventoryRangeAssetList',
      type: 'slot',
    },
  ],
  rules: {
    planName: [
      {
        required: true,
        message: '请输入名称',
        trigger: 'blur',
      },
    ],
    planStartDate: [
      {
        required: true,
        message: '请选择计划开始时间',
        trigger: 'change',
      },
    ],
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
    planResponseUser: [
      {
        required: true,
        message: '请选择计划负责人',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '140px',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const planResponseUserInfo = ref({
  //人员弹窗
  visible: false,
  saveEmpty: true,
  api: getRrgUserList,
  query: {
    statusMult: 1,
  },
})
const useDeptInfo = ref({
  visible: false,
  query: {},
  checkedRowList: [],
})
const manageDeptInfo = ref({
  visible: false,
  query: {},
  checkedRowList: [],
})
const deviceTypeInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
  checkedRowList: [],
})
const selectAssetInfo = ref({
  visible: false,
  checkedRowList: [],
  tableKey:
    'assetAssetManageAssetInventoryAddAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      depotId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      manageDeptId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      deviceType: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      useStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isAssetAchievesExcel: 'true',
      useDeptIdMult: '',
    },
  },
})
const preferenceInfo = ref({
  visible: false,
})
const formRefs = ref([])
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const selectDepotInfo = ref({
  visible: false,
  checkedRowList: [],
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 2,
    // isCargoSpaceManage: 0,
    idNotIn: '',
  },
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

watch(
  () => formInfo.value.data.inventoryLocation,
  (val) => {
    const fieldListClone = proxy.$fn.deepClone(formInfo.value.fieldList)
    if (val === 1) {
      showFieldListItem(false, 'inventoryDepotName')
      showFieldListItem(true, 'inventoryUseDeptId')
      fieldListClone[6] = {
        label: '任务拆解维度',
        value: 'splitType',
        type: 'select-model',
        code: '',
        onlyShowOption: ['1', '2', '3', '4', '5'],
      }
    } else if (val === 2) {
      showFieldListItem(true, 'inventoryDepotName')
      showFieldListItem(false, 'inventoryUseDeptId')
      fieldListClone[6] = {
        label: '任务拆解维度',
        value: 'splitType',
        type: 'select-model',
        code: '',
        onlyShowOption: ['1', '3', '4', '6'],
      }
    }
    formInfo.value.fieldList = fieldListClone
    proxy.$nextTick(() => {
      formInfo.value.fieldList[6].code = 'asset_inventory_split_type'
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [formInfo.value.rangeRef, formInfo.value.ref]
  })
})

setData()
function setData() {
  let obj = {
    depotName: {
      label: '仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    useDeptName: {
      label: '使用部门',
      value: 'useDeptName',
      slot: true,
      show: false,
      hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_inventory_plan_status',
      show: false,
      hidden: true,
    },
    inventoryPercent: {
      label: '盘点进度',
      value: 'inventoryPercent',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
  getFiscalPeriod()
}
function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.value.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      if (index > -1) {
        formInfo.value.fieldList[
          index
        ].labelTip = `当前会计期间：${res.data.name}`
        formInfo.value.fieldList[index].TimePickerOptions = {
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
            )
          },
        }
      }
    }
  })
}
function handleEventFrom(event, data) {
  if (event === 'inventoryLocation') {
    if (data === 1) {
      //盘点位置为部门，页面样式以及字段，字段限制条件与原来保持一致
      formInfo.value.data['splitType'] = 5
    } else if (data === 2) {
      //盘点位置为仓库，任务拆解维度为”不拆解、仓库、管理部门、医疗器械分类目录“，
      //默认为”仓库“，盘点范围可选项为”仓库、管理部门、医疗器械分类目录、选择资产“
      formInfo.value.data['splitType'] = 6
    }
    formInfo.value.data['inventoryUseDeptId'] = ''
    formInfo.value.data['inventoryUseDeptName'] = ''
    formInfo.value.data['inventoryDepotId'] = ''
    formInfo.value.data['inventoryDepotName'] = ''
    selectDepotInfo.value.checkedRowList = []
    useDeptInfo.value.checkedRowList = []
    formInfo.value.assetName = ''
    selectAssetInfo.value.checkedRowList = []
    selectAssetInfo.value.query.queryParams.useDeptIdMult = ''
    selectAssetInfo.value.query.queryMap.depotId.value = ''
  }
}
function selectAsset() {
  if (formInfo.value.data.inventoryLocation === 1) {
    selectAssetInfo.value.query.queryMap.useStatus.value = 2
    selectAssetInfo.value.query.queryMap.assetStatus.value = 1
  } else if (formInfo.value.data.inventoryLocation === 2) {
    selectAssetInfo.value.query.queryMap.useStatus.value = 1
    selectAssetInfo.value.query.queryMap.assetStatus.value = 3
  }
  selectAssetInfo.value.visible = true
}
function openPlanResponseUser() {
  planResponseUserInfo.value.visible = true
}
function openUseDeptWindow() {
  useDeptInfo.value.visible = true
}
function openDepotWindow() {
  selectDepotInfo.value.visible = true
}
function openManageDeptWindow() {
  manageDeptInfo.value.visible = true
}
function openDeviceTypeWindow() {
  deviceTypeInfo.value.visible = true
}
function selectDepotCallBack(row) {
  if (row && row.length) {
    let ids = row.map((item) => item.id)
    let name = row.map((item) => item.name)
    formInfo.value.data['inventoryDepotId'] = ids.toString()
    formInfo.value.data['inventoryDepotName'] = name.toString()
    formInfo.value.data['inventoryRangeAssetList'] = []
    formInfo.value.assetName = ''
    selectDepotInfo.value.checkedRowList = row
    selectAssetInfo.value.checkedRowList = []
    selectAssetInfo.value.query.queryMap.depotId.value = ids.toString()
  } else {
    formInfo.value.data['inventoryDepotId'] = ''
    formInfo.value.data['inventoryDepotName'] = ''
    selectAssetInfo.value.query.queryMap.depotId.value = ''
    selectDepotInfo.value.checkedRowList = []
  }
}
function selectPlanResponseUser(row) {
  if (row && row.id) {
    formInfo.value.data['planResponseUser'] = row.id
    formInfo.value.data['planResponseUserName'] = row.name
  } else {
    formInfo.value.data['planResponseUser'] = ''
    formInfo.value.data['planResponseUserName'] = ''
  }
}
function selectUseDeptCallback(row) {
  if (row && row.length) {
    let ids = row.map((item) => item.id)
    let name = row.map((item) => item.name)
    formInfo.value.data['inventoryUseDeptId'] = ids.toString()
    formInfo.value.data['inventoryUseDeptName'] = name.toString()
    formInfo.value.data['inventoryRangeAssetList'] = []
    useDeptInfo.value.checkedRowList = row
    selectAssetInfo.value.checkedRowList = []
    selectAssetInfo.value.query.queryParams.useDeptIdMult = ids.toString()
  } else {
    formInfo.value.data['inventoryUseDeptId'] = ''
    formInfo.value.data['inventoryUseDeptName'] = ''
    selectAssetInfo.value.query.queryParams.useDeptIdMult = ''
    useDeptInfo.value.checkedRowList = []
  }
}
function selectManageDeptCallback(row) {
  if (row && row.length) {
    let ids = row.map((item) => item.id)
    let name = row.map((item) => item.name)
    formInfo.value.data['inventoryManageDeptId'] = ids.toString()
    formInfo.value.data['inventoryManageDeptName'] = name.toString()
    formInfo.value.data['inventoryRangeAssetList'] = []
    formInfo.value.assetName = ''
    selectAssetInfo.value.checkedRowList = []
    manageDeptInfo.value.checkedRowList = row
    selectAssetInfo.value.query.queryMap.manageDeptId.value = ids.toString()
  } else {
    formInfo.value.data['inventoryManageDeptId'] = ''
    formInfo.value.data['inventoryManageDeptName'] = ''
    selectAssetInfo.value.query.queryMap.manageDeptId.value = ''
    manageDeptInfo.value.checkedRowList = []
  }
}
function selectDeviceTyprCallBack(row) {
  if (row && row.length) {
    let ids = row.map((item) => item.id)
    let name = row.map((item) => item.name)
    formInfo.value.data['inventoryDeviceType'] = ids.toString()
    formInfo.value.data['inventoryDeviceTypeValue'] = name.toString()
    formInfo.value.data['inventoryRangeAssetList'] = []
    formInfo.value.assetName = ''
    selectAssetInfo.value.checkedRowList = []
    deviceTypeInfo.value.checkedRowList = row
    selectAssetInfo.value.query.queryMap.deviceType.value = ids.toString()
  } else {
    formInfo.value.data['inventoryDeviceType'] = ''
    formInfo.value.data['inventoryDeviceTypeValue'] = ''
    selectAssetInfo.value.query.queryMap.deviceType.value = ''
    deviceTypeInfo.value.checkedRowList = []
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function handleClose() {
  dialogTipsInfo.value.visible = false
}
function pageInfo(obj) {
  page.value = obj
}
function revoke(row) {
  revokeInventoryOrderPlan([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function remove(row) {
  if (row && row.id) {
    removeByIds([row.id])
  } else if (tableInfo.value.selections.length) {
    let ids = tableInfo.value.selections.map((item) => item.id)
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        removeByIds(ids)
      })
  }
}
function removeByIds(ids) {
  deleteInventoryOrderPlan(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//保存
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let data = formInfo.value.data
      if (data.planEndDate && data.planEndDate < data.planStartDate) {
        proxy.$message({
          message: `计划结束日期不能小于计划开始日期`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      const api = data.id ? updateInventoryOrderPlan : createInventoryOrderPlan
      api(data).then((resp) => {
        if (resp && resp.success) {
          getList()
          close()
        }
      })
    }
  })
}
//关闭弹窗
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {
    planResponseUser: '',
    inventoryUseDeptId: '',
    inventoryManageDeptId: '',
    inventoryDeviceType: '',
    planResponseUserName: '',
    inventoryUseDeptName: '',
    inventoryManageDeptName: '',
    inventoryAssetTypeValue: '',
    inventoryDeviceTypeValue: '',
    inventoryRangeAssetList: [],
    businessDate: '',
    remark: '',
  }
  formInfo.value.assetName = ''
  selectAssetInfo.value.checkedRowList = []
  deviceTypeInfo.value.checkedRowList = []
  manageDeptInfo.value.checkedRowList = []
  useDeptInfo.value.checkedRowList = []
  selectDepotInfo.value.checkedRowList = []
  selectAssetInfo.value.query.queryMap.deviceType.value = ''
  selectAssetInfo.value.query.queryMap.manageDeptId.value = ''
  selectAssetInfo.value.query.queryParams.useDeptIdMult = ''
  selectAssetInfo.value.query.queryMap.depotId.value = ''
}
function checkConfirm() {
  if (dialogTipsInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogTipsInfo.value.type === 'print') {
    printList()
  }
  dialogTipsInfo.value.visible = false
  dialogTipsInfo.value.msg = ''
}
function exportExcel() {
  //导出
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'excel'
  dialogTipsInfo.value.msg = '请选择数据导出范围'
  dialogTipsInfo.value.btList[1].label = '导出'
  dialogTipsInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogTipsInfo.value.flag,
  }
  excelInventoryPlanOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  //打印
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'print'
  dialogTipsInfo.value.msg = '请选择当数据打印范围'
  dialogTipsInfo.value.btList[1].label = '打印'
  dialogTipsInfo.value.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetInventoryPlan:printOrder',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogTipsInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printInventoryPlanOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function closePlan(row = undefined) {
  //解锁
  closeInventoryOrderPlan(row.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function printOffline(row = undefined) {
  fatchTemplateByCode({
    resourceCode: 'assetInventoryPlan:printOffline',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintOfflineData(temp, row.id)
    }
  })
}
function getPrintOfflineData(temp, id) {
  let query = {
    tableKey:
      'assetAssetManageAssetInventoryPlanAssetDetails-com.slip.spd.entity.vo.asset.AssetInventoryTaskOrderDetailVO',
  }
  let params = {
    ...query,
    orderIds: [id],
  }
  inventoryPlanOrderOfflinePrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function excelOffline(row = undefined) {
  let query = {
    tableKey:
      'assetAssetManageAssetInventoryPlanAssetDetails-com.slip.spd.entity.vo.asset.AssetInventoryTaskOrderDetailVO',
  }
  let params = {
    ...query,
    orderId: row.id,
  }
  inventoryPlanOrderExcelOffline(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function confirmPlan(row = undefined) {
  confirmInventoryOrderPlan(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function callbackAsset(row) {
  console.log(row)
  if (row.length) {
    formInfo.value.data.inventoryRangeAssetList = row.map((item) => {
      return { id: item.id }
    })
    selectAssetInfo.value.checkedRowList = row
    formInfo.value.assetName = row.map((item) => item.assetName).toString()
  } else {
    selectAssetInfo.value.checkedRowList = []
    formInfo.value.data.inventoryRangeAssetList = []
    formInfo.value.assetName = ''
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//创建
function create() {
  formInfo.value.data = {
    planResponseUser: proxy.$store.state.user.userInfo.user.id,
    inventoryUseDeptId: '',
    inventoryManageDeptId: '',
    inventoryDeviceType: '',
    planResponseUserName: proxy.$store.state.user.userInfo.user.name,
    inventoryUseDeptName: '',
    inventoryManageDeptName: '',
    inventoryAssetTypeValue: '',
    inventoryDeviceTypeValue: '',
    inventoryRangeAssetList: [],
    businessDate: '',
    remark: '',
  }
  formInfo.value.assetName = ''
  dialogInfo.value.visible = true
  dialogInfo.value.title = '新增盘点计划'
  selectAssetInfo.value.checkedRowList = []
  deviceTypeInfo.value.checkedRowList = []
  manageDeptInfo.value.checkedRowList = []
  useDeptInfo.value.checkedRowList = []
  selectDepotInfo.value.checkedRowList = []
  selectAssetInfo.value.query.queryMap.deviceType.value = ''
  selectAssetInfo.value.query.queryMap.manageDeptId.value = ''
  selectAssetInfo.value.query.queryParams.useDeptIdMult = ''
  selectAssetInfo.value.query.queryMap.depotId.value = ''
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldListRange
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function update(row) {
  getInventoryOrderPlanById(row.id).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data.inventoryRangeAssetList && data.inventoryRangeAssetList.length) {
        formInfo.value.assetName = data.inventoryRangeAssetList
          .map((item) => item.assetName)
          .toString()
        selectAssetInfo.value.checkedRowList = data.inventoryRangeAssetList
        data.inventoryRangeAssetList = data.inventoryRangeAssetList.map(
          (item) => {
            return { id: item.id }
          }
        )
      }
      if (data.inventoryUseDeptId) {
        getDeptAllList('useDept', data.inventoryUseDeptId)
      }
      if (data.inventoryManageDeptId) {
        getDeptAllList('manageDept', data.inventoryManageDeptId)
      }
      if (data.inventoryDeviceType) {
        getClassificationAllList(data.inventoryDeviceType)
      }
      formInfo.value.data = data
      selectAssetInfo.value.query.queryMap.deviceType.value =
        data.inventoryDeviceType
      selectAssetInfo.value.query.queryMap.manageDeptId.value =
        data.inventoryManageDeptId
      selectAssetInfo.value.query.queryParams.useDeptIdMult =
        data.inventoryUseDeptId
      selectAssetInfo.value.query.queryMap.depotId.value = data.inventoryDepotId
      dialogInfo.value.visible = true
      dialogInfo.value.title = '修改盘点计划'
    }
  })
}
function getDeptAllList(type, ids) {
  let params = {
    idIn: ids,
  }
  getDeptAll(params).then((res) => {
    if (res && res.success) {
      if (type === 'useDept') {
        useDeptInfo.value.checkedRowList = res.data
      } else if (type === 'manageDept') {
        manageDeptInfo.value.checkedRowList = res.data
      }
    }
  })
}
function getClassificationAllList(ids) {
  let params = {
    idIn: ids,
  }
  getClassificationAll(params).then((res) => {
    if (res && res.success) {
      deviceTypeInfo.value.checkedRowList = res.data
    }
  })
}
//锁库
function publish(row = undefined) {
  publishInventoryOrderPlan(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  filterInfo.value.query.queryParams.useDeptIdMult = ''
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetAssetManageAssetInventoryPlanList-com.slip.spd.entity.vo.asset.AssetInventoryPlanOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getInventoryOrderPlanPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped lang="scss">
.dialogInfo-form-title {
  width: 100%;
  padding-left: 10px;
  color: #6dc1a9;
  margin-bottom: 20px;
  span {
    color: rgb(95, 91, 91);
    font-size: 12px;
  }
}
</style>
